#include "controlcenter.h"
#include "logger.h"

ControlCenter::ControlCenter(QObject *parent) : QObject(parent)
{
}

ControlCenter *ControlCenter::instance()
{
    static ControlCenter inst;
    return &inst;
}

ControlCenter::~ControlCenter()
{
    clearComponent();
}

void ControlCenter::addComponent(ComponentPtr component)
{
    for (int i = 0; i < m_components.count(); ++i)
    {
        if (m_components[i]->name() == component->name())
        {
            Q_ASSERT(false);
            sysError("error: component exist: %s", component->name().toStdString().data());
            break;
        }
    }

    sysDebug("add component: %s", component->name().toStdString().data());
    m_components.append(component);
}

void ControlCenter::removeComponent(ComponentPtr component)
{
    for (int i = 0; i < m_components.count(); ++i)
    {
        if (m_components[i]->name() == component->name())
        {
            if (m_components[i]->running())
            {
                sysDebug("stop component: %s", component->name().toStdString().data());
                m_components[i]->stop();
            }

            sysDebug("remove component: %s", component->name().toStdString().data());
            m_components.removeAt(i);
            break;
        }
    }
}

void ControlCenter::clearComponent()
{
    for (int i = 0; i < m_components.count(); ++i)
    {
        if (m_components[i]->running())
        {
            sysDebug("stop component: %s", m_components[i]->name().toStdString().data());
            m_components[i]->stop();
        }

        sysDebug("remove component: %s", m_components[i]->name().toStdString().data());
    }

    m_components.clear();
}

void ControlCenter::restart()
{
    stop();
    start();
}

void ControlCenter::start()
{
    for (int i = 0; i < m_components.count(); ++i)
    {
        sysDebug("start component: %s", m_components[i]->name().toStdString().data());
        m_components[i]->start();
        m_components[i]->setRunning(true);
    }
}

void ControlCenter::stop()
{
    for (int i = 0; i < m_components.count(); ++i)
    {
        sysDebug("stop component: %s", m_components[i]->name().toStdString().data());
        m_components[i]->stop();
        m_components[i]->setRunning(false);
    }
}
